//@login & register
const express = require("express");
const router = express.Router();
const db = require("../../db/index")
// const bcrypt = require("bcrypt")
const gravatar = require('gravatar');
const jwt = require('jsonwebtoken')
const key = require("../../config/key")
const passport = require("passport")


// $router GET api/user/login
// @desc 返回请token
// @access public
router.post("/login", (req, res) => {
  const { username, password } = req.body
  const sqlcc = `SELECT * FROM user WHERE name='${username}';`
  db.query(sqlcc, (err, result) => {
    if (err) {
      return err.message
    }
    if (result.length != 1) {
      return res.send({
        code: 0,
        msg: '请先注册'
      })
    } else {
      if (password == result[0].password) {
        const rule = {
          id: result[0].id,
          name: result[0].name,
          avatar: result[0].avatar,
          identity: result[0].identity
        }
        jwt.sign(rule, key.secretOrkey, { expiresIn: 3600 }, (err, token) => {
          if (err) return err.message
          return res.send({
            code: 1,
            msg: `Bearer ${token}`
          })
        })
      } else {
        return res.send({
          code: 0,
          msg: '密码错误'
        })
      }
    }
  })
})



// $router post api/user/register
// @desc 返回请求的json数据
// @access public
router.post("/register", (req, res) => {
  const { username, password, email, date, identity } = req.body
  // console.log(req.body);
  const sqlcc = `SELECT * FROM user WHERE name='${username}';`
  db.query(sqlcc, (err, reslut) => {
    if (err) {
      return err.message
    }
    if (reslut.length == 1) {
      return res.send({
        code: 0,
        msg: '名称重复，请再试一次'
      })
    } else {
      var avatars = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' });
      const sqlin = `INSERT  INTO user(name,password,email,avatar,date,identity) VALUES ('${username}','${password}','${email}','${avatars}','${date}','${identity}')`
      db.query(sqlin, (err, result) => {
        if (err) {
          return err.message
        }
        if (result.affectedRows != 1) {
          return res.send({
            code: 0,
            msg: '添加失败'
          })
        } else {
          return res.send({
            code: 1,
            msg: '添加成功'
          })
        }
      })
    }
  })
})


// $router get api/user/current
// @desc return current user
// @access private
router.get("/current", passport.authenticate("jwt", { session: false }), (req, res) => {
  // console.log(req);
  // console.log(req);
  res.send({
    code: 1,
    msg: {
      id: req.user.id,
      name: req.user.name,
      email: req.user.password,
      identity: req.user.identity
    }
  })
})


module.exports = router